# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql


class ScrapyJdPipeline:
    def __init__(self):
        self.db = pymysql.connect("localhost", "root", "Kernel990621", "jd")
        self.cursor = self.db.cursor()

    def process_item(self, item, spider):
        sql = "INSERT INTO jd(`name`, `num`, `url`, `brand`, `desc`, `seller`, `price`, `comment_num`, `praise`)" \
              "VALUES('{}', '{}', '{}', '{}', '{}', '{}', {}, {}, {})".format(item["name"], item["num"],
                                                                                item["url"], item["brand"],
                                                                                item["desc"].strip(), item["seller"],
                                                                                item["price"], item["comment_num"],
                                                                                item["praise"])
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except Exception:
            self.db.rollback()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.db.close()
